using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Generic;


public partial class UserControls_LeftMenu : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Disable ExpandDepth if the TreeView's expand/collapse
        // state is stored in session.
        //if (Session["TreeViewState"] != null)
          //  TreeView1.ExpandDepth = -1;

        if (!Page.IsPostBack)
        {
            PopulateRootLevel();


        } 
    }
    /*
    public void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
  //If the selected node is changed and we are working with the top node (If you want the ExpandCollapse func further dow, duplicate this part..)
  if (TreeView1.SelectedNode.Depth == 0)
    {
    TreeView1.CollapseAll();  //Collapse all nodes
    TreeView1.SelectedNode.Expand(); //Expand the selected node
    }
  //Save the state of the treeview
  if (IsPostBack)
  {
    List<string> list = new List<string>(16);
    SaveTreeViewState(TreeView1.Nodes, list);
    Session["TreeViewState"] = list;
  }
  //All done, lets redirect to the new page
  if (IsPostBack)
  {
  // Here i use the "value" attribute of the treeview node, this must be used instead of the NavigateURL attribute whitch makes the
  //OnSelectedNodeChange event break in the first place    
    string fw = string.Empty;
    fw = "../HunterShop/Default2.aspx?" + "DepartmentID=" + TreeView1.SelectedValue.ToString(); 
    Response.Redirect(fw.ToString());
  }
}
    //Save or reapply the state of the treeview
    protected void TreeView1_DataBound(object sender, EventArgs e)
    {
        if (Session["TreeViewState"] == null)
        {
            // Record the TreeView's current expand/collapse state.
            List<string> list = new List<string>(16);
            SaveTreeViewState(TreeView1.Nodes, list);
            Session["TreeViewState"] = list;
        }
        else
        {
            // Apply the recorded expand/collapse state to the TreeView.
            List<string> list = (List<string>)Session["TreeViewState"];
            RestoreTreeViewState(TreeView1.Nodes, list);
        }
    }
    //The save state func...
    private void SaveTreeViewState(TreeNodeCollection nodes, List<string> list)
    {
        // Recursivley record all expanded nodes in the List.
        foreach (TreeNode node in nodes)
        {
            if (node.ChildNodes != null && node.ChildNodes.Count != 0)
            {
                if (node.Expanded.HasValue && node.Expanded == true && !String.IsNullOrEmpty(node.Text))
                    list.Add(node.Text);
                SaveTreeViewState(node.ChildNodes, list);
            }
        }
    }
    //The restore state func...
    private void RestoreTreeViewState(TreeNodeCollection nodes, List<string> list)
    {
        foreach (TreeNode node in nodes)
        {
            // Restore the state of one node.
            if (list.Contains(node.Text))
            {
                if (node.ChildNodes != null && node.ChildNodes.Count != 0 && node.Expanded.HasValue && node.Expanded == false)
                    node.Expand();
            }
            else
            {
                if (node.ChildNodes != null && node.ChildNodes.Count != 0 && node.Expanded.HasValue && node.Expanded == true)
                    node.Collapse();
            }
            // If the node has child nodes, restore their state, too.
            if (node.ChildNodes != null && node.ChildNodes.Count != 0)
                RestoreTreeViewState(node.ChildNodes, list);
        }
    }*/

    private void PopulateRootLevel()
    {
        SqlConnection objConn = new SqlConnection("Server=(local)\\sqlExpress;Integrated Security=True;Database=HunterShop");
        SqlCommand objCommand = new SqlCommand(@"select DepartmentID, Name, (select count(*) FROM Category WHERE DepartmentID=Category.CategoryID) childnodecount FROM Department", objConn);

        SqlDataAdapter da = new SqlDataAdapter(objCommand);
        DataTable dt = new DataTable();
        da.Fill(dt);

        PopulateNodes(dt, TreeView1.Nodes);
    }

    private void PopulateSubLevel(int parentid, TreeNode parentNode)
    {
        SqlConnection objConn = new SqlConnection("Server=(local)\\sqlExpress;Integrated Security=True;Database=HunterShop");
        SqlCommand objCommand = new SqlCommand(@"SELECT  CategoryID, Name, (select count(*) FROM Category WHERE DepartmentID=Category.CategoryID) childnodecount FROM Category where DepartmentID=@DepartmentID", objConn);
        objCommand.Parameters.Add("@DepartmentID", SqlDbType.Int).Value = parentid;
        SqlDataAdapter da = new SqlDataAdapter(objCommand);
        DataTable dt = new DataTable();
        da.Fill(dt);
        PopulateNodes(dt, parentNode.ChildNodes);
    }


    protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);
    }

    private void PopulateNodes(DataTable dt, TreeNodeCollection nodes)
    {
        foreach (DataRow dr in dt.Rows)
        {
            TreeNode tn = new TreeNode();
            tn.Text = dr["Name"].ToString();
            if (dr.Table.Columns["DepartmentID"] != null)
                tn.Value = dr["DepartmentID"].ToString();
            if (dr.Table.Columns["CategoryID"] != null)
                tn.Value = dr["CategoryID"].ToString();
            //tn.NavigateUrl = "../Default.aspx?" + "DepartmentID=" + tn.Value;
            //tn.Target = "_topLoads";
            tn.SelectAction = TreeNodeSelectAction.SelectExpand;
            nodes.Add(tn);

            //If node has child nodes, then enable on-demand populating 
            tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);
        }
    }
    
} 

